package com.youzan.cloud.component.biz.member.common.util;
import com.youzan.cloud.base.api.BifrostService;
import com.youzan.cloud.component.token.EscrowTokenManager;
import com.youzan.cloud.component.token.OauthToken;
import com.youzan.cloud.open.sdk.api.API;
import com.youzan.cloud.open.sdk.common.exception.SDKException;
import com.youzan.cloud.open.sdk.core.client.auth.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;
/**
 * @author liling
 */
@Component
@Slf4j
public class TokenUtil {

    @Resource
    private EscrowTokenManager escrowTokenManager;

    @Autowired
    BifrostService bifrostService;

    public Token getToken(String  kdtId){
        log.info("authorityId: ===="+kdtId);
        OauthToken token = escrowTokenManager.getToken(kdtId);
        if (Objects.isNull(token)) {
            escrowTokenManager.registerAuthorityId(kdtId);
            throw new IllegalArgumentException("the oauth token of getting with using the kdtId[" + kdtId + "] not exists. ");
        }
        log.info("token: ===="+token.getAccessToken());
        return  new Token(token.getAccessToken());
    }

    public <T> T getApiResult(API object, Class<T> clazz, String kdtId){
        escrowTokenManager.registerAuthorityId(kdtId);
        OauthToken token = escrowTokenManager.getToken(kdtId);
        try {
            T result = bifrostService.invoke(object, new Token(token.getAccessToken()), clazz);
            log.info("重新刷新token调用接口成功!"+ result);
            return result;
        }catch (SDKException e){
            log.error("重新刷新token调用接口报错",e);
        }
        return  null;
    }
}
